"use client"

import { useState, useEffect } from 'react'

interface EliminationGameProps {
  targetChar: string
  onGameEnd: (score: number, correct: number, total: number) => void
}

interface GameTile {
  id: number
  content: string
  isSelected: boolean
  isEliminated: boolean
  row: number
  col: number
}

export function EliminationGame({ targetChar, onGameEnd }: EliminationGameProps) {
  const [gameGrid, setGameGrid] = useState<GameTile[][]>([])
  const [selectedTiles, setSelectedTiles] = useState<GameTile[]>([])
  const [score, setScore] = useState(0)
  const [timeLeft, setTimeLeft] = useState(60)
  const [level, setLevel] = useState(1)
  const [gameStarted, setGameStarted] = useState(false)
  const [eliminatedCount, setEliminatedCount] = useState(0)

  // 汉字池
  const characters = ['地', '坡', '池', '的', '她', '坡', '池', '的']

  // 初始化游戏
  useEffect(() => {
    initializeGrid()
  }, [])

  // 计时器
  useEffect(() => {
    if (gameStarted && timeLeft > 0) {
      const timer = setTimeout(() => {
        setTimeLeft(prev => prev - 1)
      }, 1000)
      return () => clearTimeout(timer)
    } else if (timeLeft === 0) {
      onGameEnd(score, eliminatedCount, 32) // 4x8 = 32个格子
    }
  }, [timeLeft, gameStarted, score, eliminatedCount, onGameEnd])

  const initializeGrid = () => {
    const grid: GameTile[][] = []
    let id = 0

    for (let row = 0; row < 4; row++) {
      const gridRow: GameTile[] = []
      for (let col = 0; col < 8; col++) {
        gridRow.push({
          id: id++,
          content: characters[Math.floor(Math.random() * characters.length)],
          isSelected: false,
          isEliminated: false,
          row,
          col
        })
      }
      grid.push(gridRow)
    }

    setGameGrid(grid)
    setSelectedTiles([])
    setEliminatedCount(0)
  }

  const handleTileClick = (tile: GameTile) => {
    if (!gameStarted) setGameStarted(true)
    if (tile.isEliminated) return

    const newGrid = gameGrid.map(row => 
      row.map(t => 
        t.id === tile.id 
          ? { ...t, isSelected: !t.isSelected }
          : t
      )
    )

    setGameGrid(newGrid)

    if (tile.isSelected) {
      // 取消选择
      setSelectedTiles(prev => prev.filter(t => t.id !== tile.id))
    } else {
      // 选择瓦片
      const newSelectedTiles = [...selectedTiles, tile]
      setSelectedTiles(newSelectedTiles)

      // 检查是否可以消除
      if (newSelectedTiles.length >= 2) {
        checkElimination(newSelectedTiles)
      }
    }
  }

  const checkElimination = (selected: GameTile[]) => {
    // 找到相同字符的瓦片
    const groups: { [key: string]: GameTile[] } = {}
    selected.forEach(tile => {
      if (!groups[tile.content]) {
        groups[tile.content] = []
      }
      groups[tile.content].push(tile)
    })

    // 消除成对的瓦片
    let eliminated = false
    Object.entries(groups).forEach(([char, tiles]) => {
      if (tiles.length >= 2) {
        // 消除前两个相同的瓦片
        const tilesToEliminate = tiles.slice(0, 2)
        
        const newGrid = gameGrid.map(row => 
          row.map(t => {
            if (tilesToEliminate.some(et => et.id === t.id)) {
              return { ...t, isEliminated: true, isSelected: false }
            }
            return { ...t, isSelected: false }
          })
        )

        setGameGrid(newGrid)
        setScore(prev => prev + tilesToEliminate.length * 50)
        setEliminatedCount(prev => prev + tilesToEliminate.length)
        setSelectedTiles([])
        eliminated = true
      }
    })

    if (!eliminated) {
      // 没有可消除的，清除选择
      setTimeout(() => {
        const newGrid = gameGrid.map(row => 
          row.map(t => ({ ...t, isSelected: false }))
        )
        setGameGrid(newGrid)
        setSelectedTiles([])
      }, 500)
    }
  }

  const resetGame = () => {
    setScore(0)
    setTimeLeft(60)
    setGameStarted(false)
    initializeGrid()
  }

  return (
    <div className="h-full flex flex-col bg-white rounded-2xl p-6 relative">
      {/* 游戏标题和关闭按钮 */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center space-x-3">
          <div className="w-8 h-8 bg-red-500 rounded-lg flex items-center justify-center">
            <span className="text-white text-lg">💥</span>
          </div>
          <h3 className="text-xl font-bold text-gray-800">汉字消除</h3>
        </div>
        <button
          onClick={() => onGameEnd(score, eliminatedCount, 32)}
          className="w-8 h-8 bg-red-500 rounded-full flex items-center justify-center text-white hover:bg-red-600 transition-colors"
        >
          ✕
        </button>
      </div>

      {/* 游戏状态栏 */}
      <div className="grid grid-cols-3 gap-4 mb-6">
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">{score}</div>
          <div className="text-sm text-gray-600">得分</div>
        </div>
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">
            {Math.floor(timeLeft / 60).toString().padStart(2, '0')}:
            {(timeLeft % 60).toString().padStart(2, '0')}
          </div>
          <div className="text-sm text-gray-600">时间</div>
        </div>
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">{level}</div>
          <div className="text-sm text-gray-600">关卡</div>
        </div>
      </div>
      
      {/* 游戏区域 */}
      <div className="flex-1 flex flex-col items-center justify-center">
        {/* 游戏说明 */}
        <div className="text-center mb-6">
          <div className="text-lg font-bold text-gray-700 mb-2">💥 汉字消除</div>
          <div className="text-sm text-gray-600">点击相同字根组成的汉字进行消除</div>
        </div>

        {/* 游戏网格 */}
        <div className="grid grid-cols-4 gap-3 max-w-md">
          {gameGrid.flat().map((tile) => (
            <div
              key={tile.id}
              onClick={() => handleTileClick(tile)}
              className={`
                w-16 h-16 rounded-xl flex items-center justify-center cursor-pointer
                transition-all duration-300 transform hover:scale-105 shadow-lg
                ${tile.isEliminated
                  ? 'bg-gray-200 text-gray-400 cursor-not-allowed opacity-50'
                  : tile.isSelected
                  ? 'bg-gradient-to-br from-blue-400 to-blue-500 text-white scale-105'
                  : 'bg-gradient-to-br from-pink-400 to-pink-500 hover:from-pink-500 hover:to-pink-600 text-white'
                }
              `}
            >
              <span className="text-lg font-bold">
                {tile.isEliminated ? '✓' : tile.content}
              </span>
            </div>
          ))}
        </div>

        {/* 选择提示 */}
        {selectedTiles.length > 0 && (
          <div className="mt-4 text-center">
            <div className="text-sm text-gray-600">
              已选择: {selectedTiles.map(t => t.content).join(', ')}
            </div>
          </div>
        )}
      </div>

      {/* 底部控制按钮 */}
      <div className="flex justify-center space-x-4 mt-6">
        <button 
          onClick={() => setGameStarted(!gameStarted)}
          className="px-6 py-2 bg-blue-500 text-white rounded-full hover:bg-blue-600 transition-colors flex items-center space-x-2"
        >
          <span>{gameStarted ? '⏸️' : '▶️'}</span>
          <span>{gameStarted ? '暂停' : '开始'}</span>
        </button>
        <button 
          onClick={resetGame}
          className="px-6 py-2 bg-orange-500 text-white rounded-full hover:bg-orange-600 transition-colors flex items-center space-x-2"
        >
          <span>🔄</span>
          <span>重新开始</span>
        </button>
        <button className="px-6 py-2 bg-green-500 text-white rounded-full hover:bg-green-600 transition-colors flex items-center space-x-2">
          <span>⏭️</span>
          <span>下一关</span>
        </button>
        <button 
          onClick={() => onGameEnd(score, eliminatedCount, 32)}
          className="px-6 py-2 bg-gray-500 text-white rounded-full hover:bg-gray-600 transition-colors flex items-center space-x-2"
        >
          <span>🚪</span>
          <span>退出游戏</span>
        </button>
      </div>
    </div>
  )
} 